<?php
namespace Api\Controller;

class CouponController extends APIController {
    public $tbName = CONTROLLER_NAME;

    /*待验证的参数*/
    public $tca = [
        'user_id' => [
            'method' => 'exists',
            'model' => 'member',
            'code_key' => 'lawless'
        ]
    ];

    /**
     * 列表页面-新人礼
     */
    public function index() {
        try{
            static $data = array();
            $this->safeChecked();
            $Obj = D($this->tbName); //实例化对象
            $Where = ['deleted' => 0,'type' => 3];
            $user_id = I('param.user_id',0);
            $list = [];
            $total = 0;
            if($user_id){
                //验证是否领券
                $where_coupon = array($Where,['user_id',$user_id]);
                $count = M('user_coupon')->where($where_coupon)->count();
                if(!$count){
                    $list = $Obj->where($Where)->order('crdate desc')->select()?:[];
                    $total = $Obj->where($Where)->sum('money')?:0;
                }
            }else{
                $list = $Obj->where($Where)->order('crdate desc')->select()?:[];
                $total = $Obj->where($Where)->sum('money')?:0;
            }
            $this->res_data['data'] = ['list' => $list,'total' => $total];
        }catch(\Exception $e){
            debug([$e->getmessage(),$e->getline()]);
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 新人领券
     */
    public function recevie() {
        try{
            static $data = array();
            $this->safeChecked();
            //数据验证
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $Obj = D($this->tbName); //实例化对象
            //判断用户是否已经领取新人礼包
            $user_id = I('param.user_id');
            $UserCoupon = M('user_coupon');
            $Where = ['type' => 3,'user_id' => $user_id];
            $count = $UserCoupon->where($Where)->count();
            if($count){
                $this->res_data['code_key'] = 'is_recevied';
                $this->apiReply();
            }
            $Where = ['deleted' => 0,'type' => 3];
            $list = $Obj->where($Where)->order('crdate desc')->select()?:[];
            
            //有设置新人礼包
            if($list){
                //开启事务
                $UserCoupon->startTrans();
                foreach ($list as $key => $value) {
                    $param = [
                        'user_id' => $user_id,
                        'coupon_id' => $value['id'],
                        'name' => $value['name'],
                        'type' => $value['type'],
                        'money' => $value['money'],
                        'crdate' => time(),
                        'expired' => (time() + $value['expired'] * 86400)
                    ];
                    $id = $UserCoupon->add($param);
                    //保存失败,事务回滚
                    if(!$id){
                        $UserCoupon->rollback();
                        debug($UserCoupon->_sql());
                        $this->res_data['code_key'] = 'fail';
                        $this->apiReply();
                    }
                }
                $UserCoupon->commit();
            }
            
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 列表页面
     */
    public function list() {
        try{
            static $data = array();
            $this->safeChecked();
            //数据验证
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $Obj = D('UserCoupon'); //实例化对象
            $user_id = I('param.user_id');
            $page = I('param.page',C('PAGE'));
            $show_num = I('param.show_num',C('SHOW_NUM'));
            $Where = ['user_id' => $user_id];
            $order = 'used_time asc,expired desc';
            $status = I('param.status');
            switch ($status) {
                case 1:
                    $Where['used_time'] = 0;
                    $Where['expired'] = array('gt',time());
                    $order = 'expired asc';
                    break;
                case 2:
                    $Where['used_time'] = array('gt',0);
                    $order = 'expired asc';
                    break;
                case 3:
                    $Where['expired'] = array('lt',time());
                    $order = 'expired desc';
                    break;
                default:
                    break;
            }
            $data = $Obj->where($Where)->order($order)->limit(($page -1)*$show_num,$show_num)->select()?:[];
            if($data){
                foreach ($data as $key => &$value) {
                    if($value['used_time'] == 0){
                        if($value['expired'] > time()){
                            $value['status'] = 1;
                        }else{
                            $value['status'] = 3;
                        }
                    }else{
                        $value['status'] = 2;
                    }
                    $value['expired'] = date('Y-m-d H:i',$value['expired']);
                }
            }
            $this->res_data['data'] = $data;
        }catch(\Exception $e){
            debug([$e->getmessage(),$e->getline()]);
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 用户可用优惠券
     */
    public function usableCoupon(){
        try{
            $this->safeChecked();
            /*验证*/
            $this->tca = array(
                'user_id' => array('method' => 'exists','model' => 'member','code_key' => 'lawless'),
                'money' => array('method' => 'regex','model' => '/(^[0-9]+$)|(^[0-9]+[\.]{1}[0-9]{1,2}$)/','code_key' => 'lawless'),
                'goods_id' => array('method' => 'exists','model' => 'goods','code_key' => 'lawless')
            );
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $user_id = I('param.user_id');
            $money = I('param.money');
            $goods_id = I('param.goods_id');
            $Obj = D('UserCoupon');
            $list = $Obj->visiableCoupon($user_id,$money,$goods_id);
            if($list){
                $sort = [];
                foreach($list as $val){
                    $sort[] = $val['money'];
                }
                array_multisort($sort,SORT_DESC,$list);
            }
            $this->res_data['data'] = $list?:array();
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }
}

?>